<script setup lang="ts">
import { uploadFiles } from '@/api/uploadFiles'
import BigImageComponet from '@/components/product/BigImageComponet.vue'
import SmalImageComponet from '@/components/product/SmalImageComponet.vue'
import TextComponent from '@/components/product/TextComponent.vue'
import VideoComponet from '@/components/product/VideoComponet.vue'
import { request } from '@/utils/request'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useDymicComponentStore } from '@/stores/modudels/dymicComponent'
import { getCategoryTree } from '@/api/category'
import { addOrDeleteAttr, getAttrList, getAttrListByCategoryId } from '@/api/attr'
import { getSkuCombinationStore } from '@/stores/modudels/product'
import router from '@/router'
const skuCombinationStore = getSkuCombinationStore()
const dymicComponentStore = useDymicComponentStore()
const displayContent = dymicComponentStore.displayContent
const formData = skuCombinationStore.formData

const active = ref(0)

// 分类
const categoryTree = ref([])
//接口获取的属性列表
const attrListRes = ref([])
//选择分类方法
const handleCategoryChange = async (value) => {
  formData.categoryId = value[value.length - 1]
  let arrtListResult = await getAttrListByCategoryId(formData.categoryId)
  if (arrtListResult.code === 200) {
    attrListRes.value = arrtListResult.data
    console.log('attrListRes.value:', attrListRes.value)

    skuCombinationStore.sourceData = arrtListResult.data
  }
  console.log('skuCombinationStore.sourceData:', skuCombinationStore.sourceData)

  console.log('attrListRes.value:', attrListRes.value)
  console.log('formData.value:', formData.value)
}
//页面初始化加载数据
onMounted(async () => {
  const res = await getCategoryTree()
  if (res.code === 200) {
    categoryTree.value = res.data
    //获取分类后查询属性和属性值的数据
  }
})
const next = () => {
  if (active.value++ > 2) active.value = 0
}

//点击图标动态添加组件

const fileInputBigImg = ref(null)
const fileInputSmallImg = ref(null)
const fileInputVdieo = ref(null)

const fileSmallImgList = dymicComponentStore.fileSmallImgList

//选择大图select方法
const selectBigImg = async (e: any) => {
  let imageSrc = null
  if (e.target.files[0]) {
    const file = e.target.files[0]
    if (file) {
      const result = await uploadFiles(file)
      if (result.code === 200) {
        imageSrc = result.data
        //添加组件
        let data = {
          fileData: file,
          baseData: imageSrc,
          order: displayContent.length,
          component: BigImageComponet,
          type: 'BIG_IMAGE'
        }
        dymicComponentStore.addDymicComponent(data)
        //向 form 表单中添加数据
        formData.spuContent.push({
          fileData: null,
          baseData: imageSrc,
          order: displayContent.length,
          type: 'BIG_IMAGE'
        })
      }

    }
    // 调用后端上传接口
    //const result = uploadFiles(e.target.files[0])
  }
}

// 选择小图select方法
import { findByStorageKey } from '@/utils/localStorageUtil'
import { saveSpu } from '@/api/product'
import { ElMessage } from 'element-plus'

const smallImageHeaders = ref({
  accessToken: findByStorageKey('accessToken')
})

const selectSmallImg = (e: any) => {
  if (e.target.files) {
    const files = [...e.target.files]
    console.log('files:', files)
    const reader = new FileReader()
    let imageSrcList = []

    for (const file of files) {
      imageSrcList.push(genratorLocalUrl(file))
    }
    dymicComponentStore.addDymicComponent({
      fileData: [...files],
      baseData: imageSrcList,
      order: displayContent.length,
      component: SmalImageComponet,
      type: 'SMALL_IMAGE'
    })
    console.log('dymicComponentStore.displayContent:', dymicComponentStore.displayContent)
    //向 form 表单中添加数据
    formData.spuContent.push({
      fileData: files,
      baseData: imageSrcList,
      order: displayContent.length,
      type: 'SMALL_IMAGE'
    })
  }
}

// 选择 视频 select方法
const selectVdieo = async (e: any) => {
  const videoFile = e.target.files[0]

  if (videoFile) {
    let videoUrl = null
    const result = await uploadFiles(videoFile)
    if (result.code === 200) {
      videoUrl = result.data
    }
    dymicComponentStore.addDymicComponent({
      fileData: null,
      baseData: videoUrl,
      order: displayContent.length,
      component: VideoComponet,
      type: 'VIDEO'
    })
    //向 form 表单中添加数据
    formData.spuContent.push({
      fileData: null,
      baseData: videoUrl,
      order: displayContent.length,
      type: 'VIDEO'
    })
  }
  // 调用后端上传接口
  //const result = uploadFiles(e.target.files[0])
}

// 点击图标动态添加组件
const addComponents = (type) => {
  switch (type) {
    case 'bigImage':
      //触发选择文件的行为
      fileInputBigImg.value.click()

      break
    case 'smallImage':
      //触发选择文件的行为
      fileInputSmallImg.value.click()

      break
    case 'vdieo':
      //直接添加组件
      fileInputVdieo.value.click()
      break
    case 'text':
      dymicComponentStore.addDymicComponent({
        data: '',
        order: dymicComponentStore.length,
        component: TextComponent,
        type: 'TEXT'
      })
      //向 form 表单中添加数据
      formData.spuContent.push({
        fileData: null,
        baseData: '',
        order: displayContent.length,
        type: 'TEXT'
      })
      break
  }
}

//组件改变
// const componentChange = (item, index) => {
//   console.log('componentChange:', item, index)
// }

//SKU相关属性
//级联选择器
const attrCascaderProps = {
  value: 'id',
  label: 'name',
  children: 'attrValueDTOList',
  multiple: true
}
//选择的属性
const selectCascaderValue = ref([])
//级联选择器变化方法
const cascaderChange = (value) => {
  formData.spuAttrList = []
  // selectCascaderValue :[(['5', '14'], ['5', '15'])]
  value.forEach((item) => {
    return formData.spuAttrList.push({ attrId: item[0], valueId: item[1] })
  })
  skuCombinationStore.selectedAttrValues = formData.spuAttrList
  console.log('formData.spuAttrList:', formData.spuAttrList)
  //每次选择的属性值变化都调用生成笛卡尔积
  formData.skuDetailList = skuCombinationStore.getSkuCombination()
  console.log('formData.skuDetailList:', formData.skuDetailList)
}

//sku属性组合,监听attrValueList的值变化，重新生成 attrList和attrValueList 的笛卡尔积 skuAttrList,添加进数组的对象包含三个属性{sku_attr,price,imgUrl}

// 用于存储图片预览的 URL
const imagePreviewUrl = ref('')
// 处理文件上传并生成预览
const handleFileUpload = async (event, index, row) => {
  const files = [...event.target.files]
  if (files) {
    // 生成图片预览 URL
    for (const file of files) {
      //调用后端上传接口
      const result  = await uploadFiles(file)
      //图片预览 url
      if (result.code === 200) {
        formData.skuDetailList[index].imgList.push(result.data)
      }
      // const formDataUpload = new FormData()
      // formDataUpload.append('files', file)
    }
  }
}
const removeImg = (scopIndex, imgIndex) => {
  console.log(scopIndex)
  console.log(imgIndex)
  //删除 skuAttrList 中 scopeIndex 中imgList数组中的 imgIndex元素
  formData.skuDetailList[scopIndex].imgList.splice(imgIndex, 1)
}

const onSubmit = async () => {
  console.log('formData:', formData)
  const result = await saveSpu(formData)
  if (result.code === 200) {
    ElMessage({
      message: '保存成功',
      type: 'success'
    })
    //保存成功则跳转到列表页面
    // router.push('/product/spu')
  }else {
    ElMessage({
      message: '保存失败',
      type: 'error'
    })
  }
  console.log('result:', result)
  console.log('formData:', formData)
}
// // 打开图片预览模态框11
// const openPreview = () => {
//   showModal.value = true
// }
// // 关闭图片预览模态框
// const closePreview = () => {
//   showModal.value = false
// }
</script>

<template>
  <div class="add_spu_layout">
    <!-- 头部步骤条 -->
    <div class="header_layout">
      <el-steps style="max-width: 100%" :active="active" finish-status="success">
        <el-step title="Step 1" />
        <el-step title="Step 2" />
        <el-step title="Step 3" />
      </el-steps>
    </div>

    <!-- 中间内容区域 -->
    <div class="content_layout">
      <!-- 表单 -->
      <el-form label-width="auto" label-position="left">
        <el-form-item label="选择对应分类">
          <el-cascader
            v-model="formData.categoryId"
            :options="categoryTree"
            :props="{
              value: 'id',
              label: 'name',
              children: 'child'
            }"
            @change="handleCategoryChange"
          />
        </el-form-item>
        <el-form-item label="商品标题">
          <el-input v-model="formData.title" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="商品副标题" class="desc_text_area_layout">
          <textarea
            class="text_area_class"
            v-model="formData.subTitle"
            placeholder="请输入商品副标题"
          />
        </el-form-item>

        <el-form-item label="商品详情" class="pro_detail_layout">
          <div class="item_content_display" v-for="(item, index) in displayContent" :key="index">
            <component
              :is="item.component"
              :data="{
                fileData: item.fileData,
                type: item.type,
                baseData: item.baseData,
                order: item.order
              }"
            ></component>
          </div>
          <div class="button_layout">
            <el-button icon="Picture" @click="addComponents('bigImage')">
              <input
                type="file"
                accept="image/*"
                :multiple="false"
                @change="selectBigImg"
                ref="fileInputBigImg"
                style="display: none"
              />
              大图
            </el-button>
            <el-button icon="PictureRounded" @click="addComponents('smallImage')">
              <input
                type="file"
                accept="image/*"
                :multiple="true"
                @change="selectSmallImg"
                ref="fileInputSmallImg"
                style="display: none"
              />
              小图</el-button
            >
            <el-button icon="Film" @click="addComponents('vdieo')">
              <input
                type="file"
                accept="video/*"
                :multiple="false"
                @change="selectVdieo"
                ref="fileInputVdieo"
                style="display: none"
              />视频</el-button
            >
            <el-button icon="CollectionTag" @click="addComponents('text')"> 文字</el-button>
            <el-button icon="PriceTag" @click="addComponents('tag')">标签</el-button>
          </div>
        </el-form-item>

        <el-form-item label="属性规格">
          <!-- 使用级联选择器实现 -->
          <el-cascader
            :options="attrListRes"
            :props="attrCascaderProps"
            @change="cascaderChange"
            v-model="selectCascaderValue"
          ></el-cascader>
        </el-form-item>

        <!-- sku列表 -->
        <el-form-item label="sku列表" class="sku_attr_list_layout">
          <!-- table表格 -->
          <el-table :data="formData.skuDetailList" style="width: 100%" class="sku_table_class">
            <!-- 第一列 -->
            <el-table-column prop="name" label="sku属性组合" width="180" />
            <!-- 第二列 -->
            <el-table-column prop="price" label="价格" width="180">
              <template #default="scope">
                <input type="text" v-model="scope.row.price" />
              </template>
            </el-table-column>
            <!-- 第三列: 自定义图片操作区域 -->
            <el-table-column label="图片">
              <!-- 默认插槽 -->
              <template #default="scope">
                <div class="sku_list_img_layout">
                  <!-- 图片预览区域 -->
                  <div class="image-preview-container" v-if="scope.row.imgList?.length > 0">
                    <div class="img_items" v-for="(item, index) in scope.row.imgList" :key="item">
                      <img :src="item" />
                      <el-icon @click="removeImg(scope.$index, index)" size="30" class="delete_icon"
                        ><Close
                      /></el-icon>
                    </div>
                  </div>
                  <!-- 自定义文件选择框 -->
                  <label :for="'file-input-' + scope.$index" class="custom-file-upload">
                    <el-icon size="30">
                      <Plus />
                    </el-icon>
                  </label>

                  <!-- 隐藏原生的 input -->
                  <input
                    :id="'file-input-' + scope.$index"
                    type="file"
                    accept="image/*"
                    multiple
                    style="display: none"
                    @change="handleFileUpload($event, scope.$index, scope.row)"
                  />

                  <!-- <div class="image-preview-container" v-if="imagePreviewUrl">
                    <img :src="scope.row.imgUrl" alt="Image Preview" @click="openPreview" />
                  </div> -->
                  <!-- 模态框预览 -->
                  <!-- <div v-if="showModal" class="modal" @click="closePreview">
                    <img
                      class="modal_conten_img"
                      :src="skuAttrList[scope.$index].imgUrl"
                      alt="Large Image Preview"
                    />

                  </div> -->
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 提交 -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button>Cancel</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部操作区 -->
    <!-- <div class="operation_layout">
      <el-button style="margin-top: 12px" @click="next">Next step</el-button>
    </div> -->
  </div>
</template>

<style scoped lang="scss">
.content_layout {
  .desc_text_area_layout {
    .text_area_class {
      border: 1px solid #e0e0e0;
      width: 100%;
      height: auto;
      min-height: 100px;
    }
  }
  .pro_detail_layout {
    :deep(.el-form-item__content) {
      width: 100%;
      height: auto;
      display: flex;
      flex-direction: column;
      .item_content_display {
        width: 100%;
      }
    }
  }
  .sku_attr_list_layout {
    :deep(.el-form-item__label-wrap) {
      display: flex;
      align-items: center;
    }
    .sku_list_img_layout {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      .image-preview-container {
        width: auto;
        height: 100px;
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        align-items: center;
        .img_items {
          margin-right: 10px;
          width: 80px;
          height: 80px;
          position: relative;
          border: 1px solid #ccc;
          img {
            width: 100%;
            height: 100%;
            object-fit: scale-down;
          }
          .delete_icon {
            position: absolute;
            top: -10px;
            right: -10px;
            display: none;
            background-color: #e0e0e0;
          }
          img:hover + .delete_icon {
            display: block;
          }
        }
      }
      .custom-file-upload {
        border: 2px dashed #ccc;
        width: 60px;
        height: 60px;
        margin-left: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      /* 模态框样式 */
      .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.7);
        display: flex;
        justify-content: center;
        align-items: center;
        .modal_conten_img {
          width: 80%;
          height: 80%;
          object-fit: scale-down;
        }
      }
    }
  }
}
</style>
